package com.gcloud.mesh.monitor.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.slf4j.Logger;

/**
 * 这个工具类是为了将java email的log重定向到LOG中
 * @author vger
 */
public class EmailLogUtil extends PrintStream{
	private Logger LOG;
	private static byte[] CRLF = new byte[] { 13, 10 };
	private ByteArrayOutputStream bos = new ByteArrayOutputStream();
	
	public EmailLogUtil(Logger LOG) {
		super(System.out, true);
		this.LOG = LOG;
	}

	@Override
	public void println(String str) {
		LOG.debug(str);
	}
	
	@Override
	public void write(byte buf[], int off, int len) {
		bos.write(buf, off, len);
		//到过一行末尾，输出日志
		if (len > 1) {
			if (buf[off + len - 2] == CRLF[0]
					&& buf[off + len - 1] == CRLF[1]) {
				flush();
			}
		}
	}
	
	@Override
	public void flush() {
		bos.reset();
	}
}
